import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author：徐志荣
 * @Date：2023/7/31 下午 6:56
 */
public class Day0731 {

    public static List<List<Integer>> threeSum(int[] nums) {
        //1. 排序
        Arrays.sort(nums);
        int len = nums.length;

        List<List<Integer>> ret = new ArrayList<>();
        //2.利用双指针
        for(int i = 0;i<len;){ //固定a
            if(nums[i]>0) break;  //a > 0 ;返回
            int left = i+1,right=len-1,target=-nums[i];
            while(left<right){
                int sum = nums[left] + nums[right];
                if(sum>target) right--;
                else if(sum<target) left++;
                else{
                    //nums[i] nums[left] nums[right]
                    ret.add(new ArrayList<Integer>(Arrays.asList(nums[i],nums[left],nums[right])));
                    //缩小范围
                    left++;
                    right--;
                    //去重：left right
                    while(left<right && nums[left] == nums[left-1]) left++;
                    while(left<right && nums[right] == nums[right+1]) right--;
                }
            }
            //去重 ： i
            i++;
            while(i<len && nums[i] == nums[i-1]) i++;
        }
        return ret;
    }


    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> ret = new ArrayList<>();
        int len = nums.length;

        for(int i = 0;i<len;){ //固定数a

            for(int j = i+1;j<len;){ //固定数 b
                int left = j+1, right = len-1;
                long aim = (long)target-nums[i]-nums[j];
                while(left<right){
                    int sum = nums[left]+  nums[right];
                    if(sum > aim) right--;
                    else if(sum <aim) left++;
                    else{
                        ret.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                        //不漏： 继续缩小区间去找
                        left++;
                        right--;

                        //去重 : left right
                        while(left<right&& nums[left-1] == nums[left]) left++;
                        while(left<right&& nums[right+1] == nums[right]) right--;

                    }
                }
                //去重：b
                j++;
                while(j<len&& nums[j] == nums[j-1]) j++;

            }
            //去重：a
            i++;
            while(i<len && nums[i] == nums[i-1]) i++;
        }
        return ret;
    }


    public static void main(String[] args) {
      /*  int[] arr = {-1,0,1,2,-1,-4};
        System.out.println("15. 三数之和 :" + threeSum(arr));*/

        int[] arr2 = {1,0,-1,0,-2,2};
        System.out.println("18. 四数之和 "+fourSum(arr2,0));

    }
}
